package com.iring.controller.pay;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alipay.api.AlipayClient;
import com.iring.domain.config.prop.AliPayProperties;
import com.iring.domain.config.prop.PayPalProperties;
import com.iring.domain.config.prop.PayProperties;
import com.iring.controller.BaseController;
import com.iring.domain.pay.check.PayCheck;
import com.iring.domain.pay.res.AliPayRes;
import com.iring.vo.pay.PaySuceessVO;
import com.paypal.base.rest.APIContext;

/**
 * paypal支付controller
 *
 * @author wanggan
 */
@Controller
@RequestMapping("/alipay")
public class AliPayController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(AliPayController.class);

    @Autowired
    PayPalProperties payPalProperties;

    @Autowired
    PayProperties payProperties;

    @Autowired
    APIContext apiContext;

    @Autowired
    AliPayProperties aliPayProperties;

    @Autowired
    AlipayClient alipayClient;


    @RequestMapping(value = "/add-alipay-order", method = RequestMethod.GET)
    public void addAlipayOrder(@RequestParam("orderid") String orderid, HttpServletResponse response) throws IOException {
        String username = getUserSession().getUsername();
        AliPayRes aliPayRes = payReqService.addAlipayOrder(orderid, username);
        logService.saveLog(username,"add-alipay-order",getUserRealIp(),true);
//        AliPayRes aliPayRes = payReqService.addAlipayOrder(orderid, "test222@qq.com");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(aliPayRes.getOrderHref());//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }


    @RequestMapping(value = "/repay-alipay-order", method = RequestMethod.GET)
    public void repayAlipayOrder(@RequestParam("orderid")String orderid, HttpServletResponse response) throws IOException {
        String username = getUserSession().getUsername();
        AliPayRes aliPayRes =  payReqService.repayAlipayOrder(orderid,username);
        logService.saveLog(username,"repay-alipay-order",getUserRealIp(),true);
//        AliPayRes aliPayRes =  payReqService.repayAlipayOrder(orderid,"test222@qq.com");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(aliPayRes.getOrderHref());//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }



    @RequestMapping(value = "/return",method = RequestMethod.GET)
    public String aliReturn(
            @RequestParam("app_id")String appid,
            @RequestParam("method")String method,
            @RequestParam("sign_type")String signType,
            @RequestParam("sign")String sign,
            @RequestParam("charset")String charset,
            @RequestParam("timestamp")String timestamp,
            @RequestParam("version")String version,
            @RequestParam("auth_app_id")String authAppid,
            @RequestParam("out_trade_no")String outTradeNo,
            @RequestParam("trade_no")String tradeNo,
            @RequestParam("total_amount")String totalAmout,
            @RequestParam("seller_id")String sellerId,
                          HttpServletRequest request){
        String str = request.getRequestURI();

        logger.info("alipay sync return");

        logger.info("url={}",str);
        return "redirect:"+payProperties.getSuccessUrl()+"?outTradeNo="+outTradeNo+"&totalAmout="+totalAmout;
    }

    @RequestMapping(value = "/notify",method = RequestMethod.POST)
    public void aliNotify(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        logger.info("param={}",params);
//        paramsMap.put("sign","GN9DuDeICMKkqgE2fYlIezhHYkrb1D3kSgnHPvuOVXOfps2Esq67bJitIXDdUZed9W1R+XrM5wbpH/pCS3RMAI58yb317JYREbKtyN6FDAmT3v443rcudbj2CrPRTruouD0wDL8j4PGi19bYOWh8k+hIqFXoEigsh1BVzkyDEGuE0wqIQUZ+uP6jPutl7QbvY3gyDbmg534cjg0AEU7JVDAnDhARYHFwKvHGt2GRS5zkY7kzVHWa4I9+3UlvlrW6jjHDNL9DajdzVRDGN9CeoeJfw3ioayoveRGkkX2DpSPnIsNuDHH67cotmufzcV8zu6mMO76PtQI2WimOfvnITA==");

        PayCheck basePay = payReqService.checkAlipay(params);
        if(basePay instanceof PayCheck){
            //TODO 进行下发任务
            String username = basePay.getUsername();
            simpMessagingTemplate.convertAndSendToUser(basePay.getOrderId(), "/message",
                    new PaySuceessVO(200, "支付成功", username, basePay.getRestAmounts()));

            logService.saveLog(username,"alipay notify",getUserRealIp(),true);
            response.getWriter().println("success");
        }else{
            response.getWriter().println("failure");
        }
    }
}
